import { Flex, Toast } from 'antd-mobile'
import { Component } from 'react'

import SearchHeader from '../../components/SearchHeader'
import Filter from './components/Filter'
import HouseItem from '../../components/HouseItem'
import NoHouse from '../../components/NoHouse';
import Sticky from '../../components/Sticky'

import styles from './index.module.css'

import { API } from "../../utils/api";

// 导入List组件
import { List as VirtualList, AutoSizer, WindowScroller, InfiniteLoader } from 'react-virtualized'

export default class List extends Component {
  constructor(props) {
    super(props)
    let rentType
    if (this.props.location.state) {
      rentType = this.props.location.state.rentType
      if (!rentType) {
        rentType = 'null'
      }
    }

    this.state = {
      myCityName: '',
      // 房屋信息查询参数
      params: {rentType},
      // 房屋信息列表
      housesList: [],
      // 房屋信息总数量
      count: 0,
      // 数据是否加载完成标识
      flag: false
    }
  }

  getSelectedValues = (params) => {
    if (params) {
      this.setState({
        params
      }, () => {this.getHousesList()})
    }
  }

  getHousesList = async () => {
    // 获取当前定位城市
    const { value } = JSON.parse(localStorage.getItem('hkzf_city'))
    
    Toast.loading('数据加载中...', 0)
    let res = await API({
      url: '/houses',
      params: {
        ...this.state.params,
        cityId: value,
        start: 1,
        end: 20
      }
    })
    // 页面回复到顶部
    window.scrollTo(0, 0)
    Toast.hide()

    if (res.data.body.count !== 0) {
      // 提示找到几套房源
      Toast.info(`共找到${res.data.body.count}套房源`, 1)
    }

    this.setState({
      housesList: res.data.body.list,
      count: res.data.body.count,
      flag: true
    })
  }

  // react-virtualized函数 函数返回值表示最终渲染内容
  rowRenderer({
    key, // Unique key within array of rows
    index, // Index of row within collection
    style, // Style object to be applied to row (to position it)
  }) {
    const house = this.state.housesList[index]

    if (house) {
      return (
        <HouseItem house={house} style={style} key={key} ikey={key} onClick={(house) => {this.props.history.push(`/detail/${house.houseCode}`);}}></HouseItem>
      );
    } else {
      return <div style={style} className={styles.waiting} key={key}>
        <div className={styles.imgWaiting}></div>
        <div className={styles.infoWaiting}>数据加载中...</div>
      </div>
    }
  }

  // 每一行数据是否加载完成
  isRowLoaded = ({ index }) => {
    return !!this.state.housesList[index];
  }
  
  // 加载更多数据
  loadMoreRows = ({ startIndex, stopIndex }) => {
    return new Promise(resolve => {
      API({
        url: '/houses',
        params: {
          ...this.state.params,
          start: startIndex,
          end: stopIndex
        }
      }).then(res => {
        this.setState({
          housesList: [...this.state.housesList, ...res.data.body.list]
        })
        // 数据加载完成时，调用resolve
        resolve()
      })
    })
  }

  componentDidMount() {
    // 获取当前定位城市
    if (localStorage.getItem('hkzf_city')) {
      var { label } = JSON.parse(localStorage.getItem('hkzf_city'))
    } else {
      label = '北京'
    }
    
    this.setState({
      myCityName: label
    })
    this.getHousesList()
  }

  render() {
    const { count, housesList, flag } = this.state

    return <div className={styles.list}>
      <Flex className={styles.header}>
        <i className="iconfont icon-back" onClick={() => {this.props.history.go(-1)}}/>
        <SearchHeader myCityName={this.state.myCityName} className={styles.searchHeader}/>
      </Flex>
      {/* 条件筛选栏 */}
      <Sticky  height={40} >
        <Filter getSelectedValues={this.getSelectedValues} />
      </Sticky>
      <div className={styles.housesList}>
        {
          ( housesList.length ) ? (
            <InfiniteLoader
              isRowLoaded={this.isRowLoaded}
              loadMoreRows={this.loadMoreRows}
              // 列表数据总条数
              rowCount={count}
            >
              {
                ({ onRowsRendered, registerChild }) => (
                  <WindowScroller>
                    {
                      ({ height, isScrolling, scrollTop}) => 
                        <AutoSizer>
                        {
                          ({ width }) => (
                            <VirtualList
                              autoHeight
                              onRowsRendered={onRowsRendered}
                              ref={registerChild}
                              width={width}
                              height={height}
                              isScrolling={isScrolling}
                              scrollTop={scrollTop}
                              rowCount={count}
                              rowHeight={150}
                              rowRenderer={this.rowRenderer.bind(this)}
                            />)
                        }
                        </AutoSizer>
                    }
                  </WindowScroller>
                )
              }
            </InfiniteLoader>) :
          (flag) ?
            <NoHouse>抱歉！当前筛选条件下没有房源</NoHouse> :
            null
        }

      </div>
    </div>
  }
}